#include "timer.h"
#include <avr/interrupt.h>

using namespace hw;

static TimerCallback timer_callback;

#if 0
void Timer::spawn(uint8_t mks, TimerCallback callback) {
  timer_callback = callback;
  // We will now initialize the TIMER2 clock and interrupt.
  // Clear the TIMER2 overflow flag.
  TIFR2 = static_cast<std::uint8_t>(1U << OCF2A);

  // Enable the TIMER2 compare match A interrupt.
  TIMSK2 = static_cast<std::uint8_t>(1U << OCIE2A);

  // set comparator value, /2 as 1 tick is 0.5Mhz
  OCR2A = (mks >> 2);

  // Clear OC2A on compare match
  TCCR2A = static_cast<std::uint8_t>((1U << COM2A1) | (1U << COM2A0));

  // Set the TIMER0 clock source to f_osc/32 = 0.5MHz and begin counting.
  TCCR2B = static_cast<std::uint8_t>((1U << CS21) | (1U << CS20));
}
#endif

void Timer::cancel() {
    // The Timer/Counter is inactive when no clock source is selected
    TCCR2B = 0;
}

#if 0
ISR(TIMER2_COMPA_vect) {
  TCCR2B = 0;
  timer_callback();
}
#endif


void Timer::start() {
    // Set the TIMER0 clock source to f_osc/32 = 0.5MHz and begin counting.
    TCNT0 = 0;
    TCCR0B = static_cast<std::uint8_t>((1U << CS21) | (1U << CS20));
}
